package com.acg.auth.config;


import com.acg.auth.pojo.SysLoginLog;
import com.acg.auth.service.SysLoginLogService;
import com.acg.util.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

/**
 * 登录失败的监听器
 * 当登录失败时执行登陆失败的监听器
 */
@Component
public class MyFailListence implements ApplicationListener<AbstractAuthenticationFailureEvent> {

    @Autowired
    private SysLoginLogService service;

    @Override
    public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {

        System.err.println("event"+event);


        // 1、 创建登录日志
        SysLoginLog loginLog = new SysLoginLog();

        loginLog.setStatus(false);  // 登录失败
        loginLog.setCreateTime(LocalDateTime.now());  // 创建时间
        loginLog.setAccessTime(LocalDateTime.now()); // 访问时间
        loginLog.setMsg("登录失败");
        loginLog.setUpdateTime(LocalDateTime.now());

        // ip  获取request对象

//        ServletRequestAttributes request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes request     = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        String ipAddr = IPUtils.getIpAddr(request.getRequest());
//        request.getRequestURI() // 获取路径
        loginLog.setIpaddr(ipAddr);

        /**
         * 获取此时登录的名字
         */
        Object principal = event.getAuthentication().getPrincipal();
        System.err.println("当前用户名："+principal.toString());
        // 此时登录的用户名
//        loginLog.setUsername(principal.toString());

        // 获取当前密码信息
        Object credentials = event.getAuthentication().getCredentials();
        System.err.println("密码"+credentials);

        // 增加日志
        boolean save = service.save(loginLog);

        System.out.println("日志新增："+save + "数据："+loginLog);
    }
}
